<template>
  <div class="bgImg">
    <image
      src="@/static/icon/出游.svg"
      mode="aspectFill" />
  </div>
  <div class="box">
    <div class="title">开启植物识别之旅</div>
    <div class="container">
      <uni-forms
        ref="loginForm"
        :modelValue="formData"
        :rules="rules">
        <uni-forms-item
          name="username"
          label="用户名">
          <uni-easyinput
            v-model="formData.username"
            type="text"
            placeholder="请输入用户名" />
        </uni-forms-item>

        <uni-forms-item
          name="password"
          label="密码">
          <uni-easyinput
            v-model="formData.password"
            type="password"
            placeholder="请输入密码" />
        </uni-forms-item>

        <div class="btn_box">
          <button
            type="primary"
            class="btn_login"
            @click="submit('loginForm')">
            <text v-if="isLogin">登录</text>
            <text v-else>注册</text>
          </button>
          <button
            class="btn_normal"
            @click="clearFormData">
            <text v-if="isLogin">注册</text>
            <text v-else>返回</text>
          </button>
        </div>
      </uni-forms>
    </div>
  </div>
</template>

<script>
import { toLogin, isRegister, addUser } from "@/api/user.js";
import db from "@/utils/localStorage.js";
import { mapMutations } from "vuex";

export default {
  data() {
    return {
      isLogin: true,
      formData: {
        username: "",
        password: "",
      },
      rules: {
        username: {
          rules: [
            {
              required: true,
              errorMessage: "用户名不能为空",
            },
            {
              pattern: /^[a-zA-Z0-9]+$/,
              errorMessage: "用户名只能包含字母和数字",
            },
            {
              minLength: 5,
              maxLength: 15,
              errorMessage: "用户名长度在 {minLength} 到 {maxLength} 个字符",
            },
          ],
        },
        password: {
          rules: [
            {
              required: true,
              errorMessage: "密码不能为空",
            },
          ],
        },
      },
    };
  },
  created() {
    this.checkIsLogin();
  },
  methods: {
    ...mapMutations(["setUserInfo"]),
    // 提交表单
    submit(ref) {
      this.$refs[ref]
        .validate()
        .then((res) => {
          console.log("校验成功", res);
          if (this.isLogin) {
            // 登录
            this._toLogin();
          } else {
            // 注册
            this._addUser();
          }
        })
        .catch((err) => {
          console.log("err", err);
        });
    },

    // 登录
    async _toLogin() {
      let { data: res } = await toLogin({
        username: this.formData.username,
        password: this.formData.password,
      });
      console.log("登录结果", res);
      if (res.code == 200) {
        if (res.data != null) {
          // 登录成功，信息缓存，跳转至首页
          uni.showToast({
            title: "登录成功",
            icon: "none",
            mask: false,
          });
          // 缓存信息
          this.$store.commit("setUserInfo", res.data);

          uni.reLaunch({ url: "/pages/home/home" });
        } else {
          if (await this._isRegister()) {
            // 已注册但密码错误
            uni.showToast({
              title: "密码错误",
              icon: "none",
              mask: false,
            });
          } else {
            // 未注册
            uni.showToast({
              title: "用户名不存在",
              icon: "none",
              mask: false,
            });
          }
        }
      }
    },

    // 判断是否注册
    async _isRegister() {
      let { data: res } = await isRegister({
        username: this.formData.username,
      });
      if (res.code == 200) {
        if (res.data != null) {
          // 已注册
          return true;
        } else {
          // 未注册
          return false;
        }
      }
    },

    // 注册
    async _addUser() {
      // 校验用户名是否已注册
      if (await this._isRegister()) {
        uni.showToast({
          title: "用户名已注册",
          icon: "none",
          mask: false,
        });
      } else {
        let { data: res } = await addUser({
          username: this.formData.username,
          password: this.formData.password,
        });
        if (res.code == 200) {
          uni.showToast({
            title: "注册成功",
            icon: "none",
            mask: false,
          });
          // 缓存信息，跳转至首页
          this.$store.commit("setUserInfo", res.data);
          uni.reLaunch({ url: "/pages/home/home" });
        }
      }
    },

    // 判断是否登录
    checkIsLogin() {
      let userInfo = db.get("userInfo", null);
      console.log("checkIsLogin", userInfo);
      if (userInfo != null) {
        this.$store.commit("setUserInfo", userInfo);
        // 已登录，跳转至首页
        console.log("已登录，跳转至首页", userInfo);
        uni.reLaunch({ url: "/pages/home/home" });
      }
    },

    // 清空表单
    clearFormData() {
      this.formData.password = "";
      this.formData.username = "";
      this.isLogin = !this.isLogin;
    },
  },
  // 解决在微信小程序中 样式穿透无效的问题
  options: {
    styleIsolation: "shared",
  },
};
</script>

<style lang="scss" scoped>
.box {
  position: absolute;
  top: 0;
  display: flex;
  width: 100%;
  flex-direction: column;
  gap: 16px;
  align-items: center;
}
.bgImg {
  position: relative;
  width: 100%;
  height: 100vh;
  background: linear-gradient(
    180deg,
    rgba(255, 255, 255, 0.47) 0%,
    rgba(20, 122, 230, 0.47) 100%
  );
  image {
    position: relative;
    width: 100%;
    height: 100%;
    z-index: -1;
  }
}
.title {
  margin-top: 140px;
  font-weight: 900;
  font-size: 24px;
  color: #5282ff;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  border-radius: 40px 40px 0px 0px;

  ::v-deep .uni-forms {
    display: flex;
    justify-content: center;
    width: 100%;
    margin-top: 15%;
    .uni-forms-item {
      width: 80vw;
      .uni-forms-item__label {
        display: none !important;
      }
    }
    .uni-easyinput__content {
      background-color: #f0f3fb !important;
      padding: 10px !important;
    }
    .is-input-border {
      border-radius: 25px;
      height: 50px;
      background-color: #f0f3fb;
    }
  }

  .btn_box {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .btn_login {
    background-color: #5282ff;
    color: #fff;
    width: 80vw;
    border-radius: 25px;
    font-size: 18px;
    font-weight: 700;
    line-height: 50px;
    height: 50px;

    &:active {
      background-color: #1b54d9;
      color: #ffffff;
    }
  }
  .btn_normal {
    width: 80vw;
    border-radius: 25px;
    font-size: 18px;
    font-weight: 700;
    line-height: 50px;
    height: 50px;
    background-color: #ffffff66;
    border: 1rpx solid #fff;
    color: #2c3e50;
    &:active {
      background-color: #ffffff;
    }
  }
}
</style>
